package img

import (
	"fmt"
	"go-scrcpy/internal/sink"
	"go-scrcpy/pkg"
	"go-scrcpy/pkg/log"
	"image"
	"image/png"
	"os"
	"time"
)

type Png struct {
	option  sink.Options
	fileDir string
	pix     *image.NRGBA
	count   int
}

func (c *Png) Format() pkg.MetaData {
	return pkg.MetaData{
		Size: pkg.Size{
			Width:  c.option.Width,
			Height: c.option.Height,
		},
		Format: "RGB",
	}
}

func (c *Png) Close() error {
	return nil
}

func (c *Png) Output(data []byte) error {
	c.count++
	if c.count%60 != 0 {
		return nil
	}

	f, err := os.OpenFile(fmt.Sprintf("%s/%d.png", c.fileDir, time.Now().Unix()), os.O_CREATE|os.O_TRUNC, 0666)
	if err != nil {
		log.Error("open file fail %v", err)
		return nil
	}
	c.pix.Pix = data
	err = png.Encode(f, c.pix)
	f.Close()
	return nil
}

func NewPngFileSink(fileDir string, opt ...sink.Option) sink.Sink {
	o := sink.Options{}
	for _, option := range opt {
		option(&o)
	}
	log.Info("option = %+v", o)
	rgbImage := image.NewNRGBA(image.Rect(0, 0, o.Width, o.Height))
	log.Info("creat image")
	return &Png{
		option:  o,
		pix:     rgbImage,
		fileDir: fileDir,
	}
}
